package day01;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * 流处理 word count
 *
 * @author lvbingbing
 * @date 2021-09-03 23:58
 */
public class StreamWordCount {
    public static void main(String[] args) throws Exception {
        // 1、创建执行环境
        StreamExecutionEnvironment streamingEnv = StreamExecutionEnvironment.getExecutionEnvironment();
        // 2、从程序启动参数中读取配置
        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        String host = parameterTool.get("host");
        int port = parameterTool.getInt("port");
        // 3、从 host 对应的 port 端口读取数据
        DataStream<String> dataStream = streamingEnv.socketTextStream(host, port);
        // 4、扁平化。对单词进行分组，然后用sum进行聚合
        DataStream<Tuple2<String, Integer>> wordCountDs = dataStream.flatMap(new MyFlatMapper())
                .keyBy(0)
                .sum(1);
        // 5、打印输出
        wordCountDs.print().setParallelism(1);
        // 6、触发程序执行
        streamingEnv.execute();
    }
}
